<template>
  <div class="index-container">
    <div class="shop-top">
      <div class="w1200">
        <div class="fr" ><router-link :to="`/shoplist`" title="融易装">
              <i class="el-icon-house" style="margin-right:5px;"></i>首页
            </router-link></div>
        <div class="fl">
          <div class="sn-quick-menu">
            <div class="login"><img v-if="info.logo"
                   :src="info.logo.path"
                   alt="">{{info.name?info.name:'暂未设置'}}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="header">
      <div class="headerLayout w1200">
        <div class="headerCon">
          <h1 class="mallLogo">
            <router-link :to="`/shoplist`"
                         title="融易装">
              <img src="../img/logo.png">
            </router-link>
          </h1>
          <div class="mallSearch">
            <form action=""
                  class="layui-form"
                  novalidate>
              <input type="text"
                     v-model="keyword"
                     class="layui-input"
                     placeholder="搜索关键字">
              <button class="layui-btn"
                      @click="filterPops()">
                <i class="el-icon-search"></i>
              </button>
            </form>
          </div>
        </div>
      </div>
    </div>

    <div class="content content-nav-base commodity-content">

      <div class="main-nav">
        <div class="inner-cont0">
          <div class="inner-cont1 w1200">
            <div class="category-types"
                 style="">
              <h3>全部分类</h3>
            </div>
            <div class="inner-cont2">
              <router-link :to="`/nowlist`">选材中心</router-link>
              <router-link :to="`/orderlist`">我的订单</router-link>
              <router-link :to="`/nowadderss`">地址管理</router-link>
              <router-link :to="`/nowcart`" class="active">购物车</router-link>
            </div>
          </div>
        </div>
      </div>

      <div class="commod-cont-wrap"
           style="background:#f8f8f8;">
        <div class="commod-cont w1200 layui-clear">
          <div class="order-top">我的购物车 <span style="float:right;font-weight: normal;">共{{totalLength}}件家具</span></div>
          <div class="tablist">
            <!-- 购物车页面内容 -->
            <section class="shopcartContainer">
                <div class="shopcartContainerMain">
                  <table class="cont1 mobile_hidden"><!--PC端购物车-->
                    <tr class="title_tr">
                      <th style="width: 60px;"><span class="c_sSelect" :class="{'active': isAllSelect}" @click="selectAll"></span>全选</td>
                      <th style="width: 60px;"></th>
                      <th style="width: 310px;">商品</th>
                      <th style="width: 130px;">规格</th>
                      <th style="width: 130px;">单价</th>
                      <th style="width: 160px;">数量</th>
                      <th style="width: 100px;">操作</th>
                    </tr>
                    <tr class="br"><td colspan="8"><!--分割线--></td></tr>
                    <template v-for="(items,index) in cart">
                    <tr class="merchant"><td colspan="8"><span style="margin-top: 2px;margin-right:5px;float:left;" class="c_cSelect" :class="{'active': items.select}" @click="selectShop(items.store_id)"></span>{{items.store_name}}</td></tr>
                    <tr v-for="(item,index) in items.products" :key="index">
                      <td><span class="c_cSelect" :class="{'active': item.select}" @click="selectGoods(items.store_id, item.cart_id)"></span></td>
                      <td><img :src="item.main_imgurl" class="shopImg"/></td>
                      <td>
                        <router-link class="shopName" :to="{path:'/shopdeatil',query: {product_id: item.product_id}}">{{item.product_title}}</router-link>
                      </td>
                      <td><p v-for="(item2,index2) in item.attribute" :key="index2">{{item2.value}}</p></td>
                      <td><p class="cost_price">底价:￥<span>{{item.cost_price}}</span></p><p class="s_price">售价:￥<span>{{item.price}}</span></p><p class="s_price">原价:￥<span>{{item.primary_price}}</span></p></td>
                      <td>
                        <div class="cpay_nums">
                          <div class="c_cnMinus el-icon-minus" @click="minusCart(items.store_id,item)"></div>
                          <div class="c_cnpay_num">{{item.cart_num}}</div>
                          <div class="c_cnAdd el-icon-plus" @click="addCart(items.store_id,item)"></div>
                        </div>
                      </td>
                      <td> <span class="delBtn" @click="Cartdel(item.cart_id)">删除</span> </td>
                    </tr>
                    <tr class="br"><td colspan="8"><!--分割线--></td></tr>
                    </template>
                  </table>
                  <div class="checkoutCont mobile_hidden">
                    <input class="subBtn" type="button" value="结算" @click="toCartList"/>
                    <p class="allPrice">总价: <b>￥{{sumCostPrice}}</b></p>
                    <label class="all"><span style="margin-top: 11px;" class="c_sSelect" :class="{'active': isAllSelect}" @click="selectAll"></span>全选</label>
                    <span class="delBtn" @click="minusCartAll">删除</span>
                    <span style="cursor: pointer;" @click="daochuOrder()">导出清单</span>
                  </div>
                </div>   
            </section>
          </div>
     
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="ng-promise-box">
        <div class="ng-promise w1200">
          <p class="text">
            <a class="icon1"
               href="javascript:;">7天无理由退换货</a>
            <a class="icon2"
               href="javascript:;">送货上门</a>
            <a class="icon3"
               style="margin-right: 0"
               href="javascript:;">100%品质保证</a>
          </p>
        </div>
      </div>
      <div class="mod_help w1200">
        <!-- <p>
        <a href="javascript:;">关于我们</a>
        <span>|</span>
        <a href="javascript:;">帮助中心</a>
        <span>|</span>
        <a href="javascript:;">售后服务</a>
        <span>|</span>
        <a href="javascript:;">行业资讯</a>
        <span>|</span>
        <a href="javascript:;">关于货源</a>
      </p> -->
        <p class="coty">融易装版权所有 &copy; 2012-2020</p>
      </div>
    </div>

  </div>
</template>

<script>
  import QRCode from 'qrcodejs2'
  export default {
    data() {
      return {
        name: '小刀',
        info: {},
        mobile: '',
        cart: null,
				productcart: [],
				isAllSelect: false, // 是否全选中
				productAllSelect: false, // 是否全选中
				productPrice: 0,
				productCostPrice: 0,
				sumPrice: 0,
				sumCostPrice: 0,
				flag: false,
				productflag: false,
				tab: 1,
        keyword:'',
      }
    },
    mounted() {
      this.info = JSON.parse(localStorage.getItem('info'))
      this.mobile = localStorage.getItem('mobile')
       this.getCartList()
    },
    computed: {
			totalLength() {
				if (this.cart && this.cart.length > 0) {
					let total = 0;
					this.cart.map(item1 => {
						if (item1.products && item1.products.length > 0) {
							total += item1.products.length
						}
					})
					return total
				} else {
					return 0
				}
			},
			productLength() {
				if (this.productcart && this.productcart.length > 0) {
					let total = 0;
					total += this.productcart.length
					return total
				} else {
					return 0
				}
			},
		},
    methods: {
      filterPops(){
        this.$router.push({name:'nowlist',query:{keyword:this.keyword}})
      },
      // 获取购物车
      getCartList() {
        this.$http.post('/api/admin/shopweb/cart/lists', { 
          store_id: 0
         }).then(res => {
          if (res.code == 1) {
							this.cart = res.data
							// this.productcart = res.data.pack
							this.verifyAllSelect() // 验证是否所有店铺所有商品是否都已选中
							this.countPrice() // 计算价格
						}
        })
      },
      // 选择店铺
			selectShop(store_id) {
				let cart = this.cart
				let shop = cart.find(val => val.store_id == store_id)
				// 全选or全不选
				shop.select = !shop.select
				shop.products.forEach(val => val.select = shop.select)

				this.verifyAllSelect() // 验证是否所有店铺所有商品是否都已选中
				this.countPrice() // 计算价格
      },
      // 选择商品
			selectGoods(store_id, id) {
				let cart = this.cart
				let shop = cart.find(val => val.store_id == store_id)
				let goods = shop.products.find(val => val.cart_id == id)

				// 选中or不选中
				goods.select = !goods.select
				// 判断该店铺下商品是否已全选
				let flag = true
				shop.products.forEach(val => {
					if (!val.select) flag = false
				})
				if (shop.select != flag) shop.select = flag

				this.verifyAllSelect() // 验证是否所有店铺所有商品是否都已选中
				this.countPrice() // 计算价格
      },
      // 全选or全不选
			selectAll() {
				this.isAllSelect = !this.isAllSelect
				this.cart.forEach(val => {
					val.select = this.isAllSelect
					val.products.forEach(v => v.select = this.isAllSelect)
				})
				this.verifyAllSelect() // 验证是否所有店铺所有商品是否都已选中
				this.countPrice() // 计算价格
			},

			// 验证所有商品是否全选
			verifyAllSelect() {
				let isAll = this.cart.find(val => !val.select) ? false : true
				if (this.isAllSelect != isAll) this.isAllSelect = isAll
			},

			// 计算价格
			countPrice() {
				let price = 0,
					cost_price = 0
				this.cart.forEach(val => {
					val.products.forEach(v => {
						if (v.select) {
							price = this.accAdd(price, this.accMul(v.cart_num, v.price))
							cost_price = this.accAdd(cost_price, this.accMul(v.cart_num, v
								.cost_price))
						}
					})
				})

				this.sumPrice = price
				this.sumCostPrice = cost_price
      },
      // 添加商品
			addCart(store_id, item) {
				let cart = this.cart
				let shop = cart.find(val => val.store_id == store_id)
				let goods = shop.products.find(val => val.cart_id == item.cart_id)
				goods.cart_num++
        this.countPrice() // 计算价格
        this.$http.post('/api/admin/shopweb/cart/setnum', { 
          id: item.cart_id,
					num: goods.cart_num,
					action:'inc',
         }).then(res => {
          
        })
   
      },
      // 删减商品
			minusCart(store_id,item) {
				console.log(item)
				let cart = this.cart
				let shop = cart.find(val => val.store_id == store_id)
				let goods = shop.products.find(val => val.product_id == item.product_id)
				if (goods.cart_num > 1) {
					goods.cart_num--
					this.countPrice() // 计算价格
          this.$http.post('/api/admin/shopweb/cart/setnum', { 
            id: item.cart_id,
              num: goods.cart_num,
              action:'dec',
          }).then(res => {
            
          })
				} else {
          this.$confirm('确认删除该商品? 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
               this.$http.post('/api/admin/shopweb/cart/del', { 
                    id: item.cart_id,
                }).then(res => {
                  if (res.code == 1) {
										this.getCartList()
									}
                })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
				}
      },
      Cartdel(id){
        this.$confirm('确认删除该商品? 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
               this.$http.post('/api/admin/shopweb/cart/del', { 
                    id: id,
                }).then(res => {
                  if (res.code == 1) {
										this.getCartList()
									}
                })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
      },
      // 删减多选商品
			minusCartAll() {
				let ids = [];
				this.cart.map(item1 => {
					if (item1.products && item1.products.length > 0) {
						item1.products.map(item2 => {
							if (item2.select) {
								ids.push(item2.cart_id)
							}
						})
					}
				})
				if (ids.length < 1) {
          this.$message({
              type: 'info',
              message: '请先选择删除的商品！'
            });
					return
        }
        this.$confirm('确认删除该项? 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
               this.$http.post('/api/admin/shopweb/cart/del', { 
                  id: ids.join(","),
                }).then(res => {
                  if (res.code == 1) {
										this.getCartList()
									}
                })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
      },
      toCartList(){
         if (!this.cart.length) {
            this.$message({
              type: 'info',
              message: '暂无可结算商品，再看看吧！'
            });
						return
					} else {
						let ary = []
						this.cart.forEach(val => {
							val.products.forEach(v => {
								if (v.select) {
									ary.push(
										v.cart_id
									)
								}
							})
						})
						if (!ary.length) {
              this.$message({
                type: 'info',
                message: '先选择结算产品'
              });
							return
						}
						let params = {
							origin_type: 1,
							cart_ids: ary.join(),
							goods: ''
						}
						console.log(params)
						localStorage.setItem('params',JSON.stringify(params))
            this.$router.push({name:'order',query:{}})
					}
      },
      // 导出清单
      daochuOrder() {
        const user_id = localStorage.getItem('user_id')?localStorage.getItem("user_id"):"";
        let ary = []
						this.cart.forEach(val => {
							val.products.forEach(v => {
								if (v.select) {
									ary.push(
										v.cart_id
									)
								}
							})
						})
						if (!ary.length) {
              this.$message({
                type: 'info',
                message: '先选择清单产品'
              });
							return
				}
        this.$confirm('此操作将导出该清单', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          window.open('/api/admin/shopweb/cart/export?idlst='+ ary.join() + '&user_id=' + user_id  ) 
        }).catch(() => {
                 
        });
      },
         // js加法
	accAdd(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2))
		return (this.accMul(arg1, m) + this.accMul(arg2, m)) / m;   
	},

	// js减法
	accSub(arg1, arg2) {
		let r1, r2, m
		try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
		try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
		m = Math.pow(10, Math.max(r1, r2));
		return (this.accMul(arg1, m) - this.accMul(arg2, m)) / m;  
	},

	// js乘法
	accMul(arg1, arg2) {
		let m = 0, s1 = arg1.toString(), s2 = arg2.toString()
		try { m += s1.split(".")[1].length } catch (e) { }
		try { m += s2.split(".")[1].length } catch (e) { }
		return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
	},

	// js除法
	accDiv(arg1, arg2) {    
		let t1 = 0, t2 = 0, r1, r2 
		try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
		try { t2 = arg2.toString().split(".")[1].length } catch (e) { }   
		r1 = Number(arg1.toString().replace(".", ""))    
		r2 = Number(arg2.toString().replace(".", ""))    
		return (r1 / r2) * Math.pow(10, t2 - t1)  
	},
    }
  }
</script>
<style lang="less" scoped>
  & /deep/ .content {
    padding: 0 !important;
  }
  @import "../css/index.less";
</style>
